// Package dao
// @Author zhongxc
// @Date 2024/5/13 15:39:00
// @Desc
package dao

import (
	"context"
	"errors"
	"gorm.io/gorm"
	"math"
	"project-common/msdb"
	"project-common/msdb/gorms"
	"project-user/pkg/model"
)

type UserDao struct {
	conn *gorms.GormConn
}

func NewUserDao(db *msdb.MsDB) *UserDao {
	return &UserDao{
		conn: gorms.New(db.Conn),
	}
}

func (u *UserDao) GetUserById(ctx context.Context, userId int64) (*model.User, error) {
	/*
		userKey := "user:" + strconv.FormatInt(userId, 10)
		userInfo, err := cache.Rc.Get(ctx, userKey)
		if err != nil {
			return nil, err
		}
		if userInfo != "" {
			user := model.User{}
			err := json.Unmarshal([]byte(userInfo), &user)
			if err != nil {
				return nil, err
			}
			return &user, nil
		}
	*/
	var user model.User
	session := u.conn.Session(ctx)
	err := session.Where("user_id = ?", userId).Limit(1).Take(&user).Error
	if errors.Is(err, gorm.ErrRecordNotFound) {
		return nil, nil
	}
	/*
		marshal, err := json.Marshal(user)
		if err != nil {
			return nil, err
		}
		err = cache.Rc.Put(ctx, userKey, string(marshal), 600*time.Second)
		if err != nil {
			return nil, err
		}
	*/
	return &user, err
}

func (u *UserDao) GetUserList(ctx context.Context, page, pageSize int64) (map[string]interface{}, error) {
	session := u.conn.Session(ctx)
	// 总记录数
	var totalCount int64
	session.Find(&model.User{}).Count(&totalCount)

	// 总页数
	pageCount := math.Ceil(float64(totalCount) / float64(pageSize))

	var users []*model.User
	// 偏移量
	offset := (page - 1) * pageSize
	err := session.Limit(int(pageSize)).Offset(int(offset)).Order("user_id desc").Find(&users).Error
	if err != nil {
		return nil, err
	}

	var result = make(map[string]interface{})

	result["list"] = users
	result["total"] = totalCount
	result["pageCount"] = pageCount
	result["pageSize"] = pageSize
	result["page"] = page

	return result, nil
}
